<?PHP
session_start();
include_once "ini.php";
$id_chat = $_POST['id_chat'];
dbconnect();
//supp l'id ds user et supp les conversation ds chat
$sql = "SELECT * FROM users WHERE id_user = '".$_SESSION['id_user']."';";
$requete = mysql_query($sql);
if (!$requete)
{
    echo "SQL error : ", $sql;
    exit ;
}
else
{
    while ($tab = mysql_fetch_assoc($requete))
    {
        $chat_online = $tab['chat'];
        $chat_people = split(":", $chat_online);

        
        if (count($chat_people) != 0)
        {
            $chat_online = "";
            for ($i = 0; $i < count($chat_people); $i++)
            {
                if ($chat_people[$i] != $id_chat)
                {
                    $chat_online .= $chat_people[$i].":";
                }
            }
            $chat_online = substr($chat_online, 0, strlen($chat_online)-1);
           
        }
        else
        {
            echo "chat vide";
        }
        $query = "UPDATE `users` SET `chat` = '".$chat_online."' WHERE `users`.`id_user` = '".$_SESSION['id_user']."' LIMIT 1 ;";
        $result = mysql_query($query);
        if (!$result)
        {
            echo "SQL error : ", $query;
            exit ;
        }
        
    }
}

$query = "SELECT * FROM users WHERE id_user = '".$id_chat."';";
$result = mysql_query($query);
if (!$result)
{
    echo "SQL error : ", $query;
    exit ;
}
else
{
    $tab = mysql_fetch_assoc($result);
    $chatteur = split(":", $tab['chat']);
    $test = in_array($_SESSION['id_user'], $chatteur);
    if ($test == false)
    {
        $correspondants = ($id_chat < $_SESSION['id_user'])?$id_chat.":".$_SESSION['id_user']:$_SESSION['id_user'].":".$id_chat;
        $sql = "DELETE FROM chat WHERE correspondants = '".$correspondants."';";
        $requete = mysql_query($sql);
        if (!$requete)
        {
            echo "SQL error : ", $sql;
            exit ;
        }
    }
}
dbclose();
?>
